#include <bits/stdc++.h>

using namespace std;
struct node{
    int val;
    struct node *left,*right;
};
int in[10010],pre[10010],pos[10010],M,N;
unordered_map<int,bool> isValid;

int dfs(int inl,int inr,int prel,int prer,int a,int b){
    if(pre[prel]==a || pre[prel]==b) return pre[prel];
    int i;
    while(in[i]!=pre[prel]) i++;
    if(pos[in[i]]<pos[a] && pos[in[i]]<pos[b]) return dfs(i+1,inr,prel+i-inl+1,prer,a,b);
    else if(pos[in[i]]>pos[a] && pos[in[i]]>pos[b]) return dfs(inl,i-1,prel+1,prel+i-inl,a,b);
    else return pre[prel];
}

int main(){
    freopen("../A1151.txt","r",stdin);
    cin>>M>>N;

    for(int i=1;i<=N;i++) {
        cin>>in[i];
        pos[in[i]] = i;
        isValid[in[i]] = true;
    }
    for(int i=1;i<=N;i++) {
        cin>>pre[i];
        isValid[pre[i]] = true;
    }

    int a,b;
    while(M--){
        cin>>a>>b;
        if(!isValid[a] && !isValid[b]) {
            printf("ERROR: %d and %d are not found.\n",a,b);
            continue;
        }else if(!isValid[a]){
            printf("ERROR: %d is not found.\n",a);
            continue;
        }else if(!isValid[b]){
            printf("ERROR: %d is not found.\n",b);
            continue;
        }

        int result = dfs(1,N,1,N,a,b);

        if(result!=a && result!=b){
            printf("LCA of %d and %d is %d.\n",a,b,result);
        }else{
            if(result==a) printf("%d is an ancestor of %d.\n",a,b);
            else printf("%d is an ancestor of %d.\n",b,a);
        }
    }
}